#!/usr/bin/env python3
import os
import re
import record_system_info
import stat_history_vdbench
from pathlib import Path

def replace_line_in_file(line_number, new_content, file_append):

    file = open("./stat_vdbench.max_" + file_append, 'r')

    lines = file.readlines()

    file.close()

    lines[line_number] = new_content


    file = open("./stat_vdbench.max_" + file_append, 'w')

    file.writelines(lines)

    file.close()


def get_max(score, sys_value, sys_path, vdbench_command, item):

    tmp = sys_path
    file_append = ""
    tmpidx = tmp.find("value:")
    if tmpidx != -1:
        file = tmp[ 6: tmpidx - 1].strip()
        file_append = re.sub("/", "_", file)
    file = open("./stat_vdbench.max_" + file_append, 'a')
    file.close()

    data_max_get = open("./stat_vdbench.max_" + file_append, 'r+')
    line = -1
    for _l in data_max_get.readlines():
        _ll = _l.strip()
        line += 1
        # skip null lines
        if not _ll:
            continue

        # skip comment lines
        if _ll.find("#") == 0:
            continue
        
        #item
        tmpidx = _ll.find("item:")
        if tmpidx == -1:
            continue
        max_item = _ll[tmpidx + 5: ].strip()
        if max_item != item:
            continue

        #sys value
        tmpidx = _ll.find("value:")
        if tmpidx == -1:
            continue
        tmp_value = _ll[tmpidx + 6:].strip();
        #if int(tmp_value) != sys_value:
        #    continue

        #command value
        tmpidx = _ll.find("vdbench")
        if tmpidx == -1:
            continue
        eidx = _ll.find("paremater:")
        if eidx == -1:
            continue
        tmp_command = _ll[tmpidx: eidx - 1].strip()
        if tmp_command != vdbench_command:
            continue

        tmpidx = _ll.find("command:")
        if tmpidx == -1:
            continue
        qpsidx = _ll.find("qps:")
        if qpsidx == -1:
            continue
        old_max = _ll[qpsidx + 4: tmpidx - 1].strip()
        if float(old_max) >= score:
            return False
        new_content = "result qps:" + str(score) + " command:" + vdbench_command + " paremater:" + sys_path + " item:" + item + "\n"
        data_max_get.close()
        replace_line_in_file(line, new_content, file_append)
        return True
    data_max_get.close()

    data_max = open("./stat_vdbench.max_" + file_append, 'a')
    new_content = "\nresult qps:" + str(score) + " command:" + vdbench_command + " paremater:" + sys_path  + " item:" + item + "\n"
    data_max.write(new_content)
    data_max.close()
 
    return True

def stat_file(_f, delay):
    data_out = open("./stat_vdbench.file", 'w+')
    sys_path = ""
    sys_value = ""
    for root, dirs, files in os.walk("./history_vdbench", topdown=True):
        for name in files:
            fname = os.path.join(root, name)
            if name.endswith(".swp"):
                continue
            with open(fname, 'r') as _fd:
                for _l in _fd.readlines():
                    _ll = _l.strip()

                    # skip null lines
                    if not _ll:
                        continue

                    # skip comment lines
                    if _ll.find("#") == 0:
                        continue

                    # skip other files
                    if _ll.find(_f) == 0:
                        continue
                    #create files

                    tmpidx = _ll.find("file:")
                    if tmpidx != -1:
                        sys_path = _ll[tmpidx:].strip()
                        tmpidx = _ll.find("value:")
                        if tmpidx != -1:
                            sys_value = _ll[tmpidx + 6:].strip();
                        continue

                    tmpidx = name.find("vdbench")
                    if tmpidx == -1:
                        continue
                    filename = name[tmpidx:]
                    if filename == "vdbench_create_files" or filename == "vdbench_delete_files":
                        result_stat ="avg_2-" + delay
                        tmpidx = _ll.find(result_stat)
                        avg = tmpidx
                        if (tmpidx == -1):
                            result_stat ="std_2-" + delay
                            tmpidx = _ll.find(result_stat)
                            if (tmpidx == -1):
                                result_stat ="max_2-" + delay
                                tmpidx = _ll.find(result_stat)
                        if tmpidx != -1:
                            key = _ll[tmpidx + len(result_stat) + 1 : ].strip()
                            black_space_idx = key.find(" ")
                            key = key[ : black_space_idx]
                            print("result " + result_stat + ":" + key + " command:" + filename + " paremater:" + sys_path + "\n", file=data_out, end=' ', flush=True)
                            tmp_result = get_max(float(key), int(sys_value), sys_path, filename, result_stat)
                            if avg != -1 and tmp_result == True:
                                file_append = ""
                                tmp = sys_path
                                fileidx = tmp.find("value:")
                                if fileidx != -1:
                                    file = tmp[ 6 : fileidx - 1].strip()
                                    file_append = re.sub("/", "_", file)
                                record_system_info.recore_max_info(fname + "_info_max", file_append)
                            #print("result qps:" + str(tmp_result) + " thds:" + threads + " paremater:" + sys_path + "\n", file=data_max_tmp, end=' ', flush=True)
                        continue

                    result_stat ="avg_2-" + delay
                    tmpidx = _ll.find(result_stat)
                    avg = tmpidx
                    if (tmpidx == -1):
                        result_stat ="std_2-" + delay
                        tmpidx = _ll.find(result_stat)
                        if (tmpidx == -1):
                            result_stat ="max_2-" + delay
                            tmpidx = _ll.find(result_stat)
                    if tmpidx != -1:
                        key = _ll[tmpidx + len(result_stat) + 1 : ].strip()
                        black_space_idx = key.find(" ")
                        key = key[ : black_space_idx]
                        print("result " + result_stat + ":" + key + " command:" + filename + " paremater:" + sys_path + "\n", file=data_out, end=' ', flush=True)
                        tmp_result = get_max(float(key), int(sys_value), sys_path, filename, result_stat)
                        if avg != -1 and tmp_result == True:
                            file_append = ""
                            tmp = sys_path
                            fileidx = tmp.find("value:")
                            if fileidx != -1:
                                file = tmp[ 6 : fileidx - 1].strip()
                                file_append = re.sub("/", "_", file)
                            record_system_info.recore_max_info(fname + "_info_max", file_append)
                        #print("result qps:" + str(tmp_result) + " thds:" + threads + " paremater:" + sys_path + "\n", file=data_max_tmp, end=' ', flush=True)
                        continue

    data_out.close()

def do_the_stat(delay):

    file = open("./stat_vdbench.file", 'a')
    file.close()

    file = open("./stat_vdbench_all.file", 'a')
    file.close()

    stat_file("vdbench", delay)

    stat_history_vdbench.do_the_stat_history(delay)

    file_tmp = open("./stat_vdbench.file", 'r')
    file_all = open("./stat_vdbench_all.file", 'a+')
    data = file_tmp.read()
    file_all.write(data)
    file_tmp.close()
    file_all.close()

    #os.unlink()
